package be.groept.ace.enquete.servlets;

import java.io.IOException;
import java.util.SortedSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.Survey;
import be.groept.ace.enquete.model.dao.DAOCommand;
import be.groept.ace.enquete.model.dao.DAOFactory;
import be.groept.ace.enquete.model.dao.DAOManager;
import be.groept.ace.enquete.model.exceptions.DAOException;

/**
 * Servlet implementation class AdminEnquetesServlet
 */
@WebServlet({ "/admin/enquetes/*", "/admin/*" })
public class AdminEnquetesServlet extends AdminServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AdminEnquetesServlet.class);

	@Override
	protected int handleGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession(false);
		setPage(request, "enquetes");
		setTitle(request, "Beheer enquetes");
		setNavigationSelectedLink(request, 1);
		
		String link;
		if(session.getAttribute("survey") == null) {
			link = "Nieuw";
		} else {
			link = "Editeer enquete";
		}
		addHeaderLink(request, 1, link, response.encodeURL(request.getContextPath() + "/admin/enquete"));	
		
		DAOManager daoManager = null;
		try {
			daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
		} catch (DAOException daoe) {
			logger.fatal(daoe.toString());
			throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
		}
		
		try {
			//ik ben zeker dat de transactie me een SortedSet<Survey> gaat teruggeven!
			@SuppressWarnings("unchecked") 
			SortedSet<Survey> surveys = (SortedSet<Survey>) daoManager.transaction(new DAOCommand() {
				
				@Override
				public Object execute(DAOManager daoManager) throws DAOException {
					return daoManager.getSurveyDAO().findAllSurveys();
				}
			});
			
			request.setAttribute("enquetes", surveys);
			
		} catch (DAOException daoe) {
			logger.fatal(daoe.toString());
			throw new ServletException(daoe.getMessage());
		}
		return 200;
	}

	@Override
	protected int handlePost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		return 404;
	}

    
}
